package com.hooper.executor.demo;

import cn.hutool.core.util.RandomUtil;
import org.junit.jupiter.api.Test;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author Tim Hooper
 * @version 1.0
 * @time 2023/03/02/21:25
 */
public class TestCachedThreadPool {
    @Test
    public void test1() {
        //空参创建
        ExecutorService es = Executors.newCachedThreadPool();
        for (int i = 0; i < 10; i++) {
            es.submit(new MyTask());
        }
    }

    @Test
    public void test2() {
        //基于ThreadFactory创建；可对线程进行设置 如：名称，优先级等
        ExecutorService es = Executors.newCachedThreadPool(r ->
                new Thread(r, "my task" + RandomUtil.randomInt(1, 100)));
        for (int i = 0; i < 10; i++) {
            es.submit(new MyTask());
        }
    }


}

class MyTask implements Runnable {

    @Override
    public String toString() {
        return "id" + Thread.currentThread().getId() + "";
    }

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName() + " run >>>");
    }
}